#include "dirFunc.h"

int cd(char *dirName,Link_list_t *list){ 
    //if(dirName==NULL){
    //    while(list->length!=0){
    //        delete_catalog(list);
    //    }
    //    printf("/home/netdisk/C++66/");
    //    return 0;
    //}
    if(access(dirName,F_OK)!=0){
        printf("该文件不存在\n");
        return -1;;
    }

    char *delim="/";    
    char path[1024];
    strncpy(path, dirName, sizeof(path)-1);
    path[sizeof(path)-1] = '\0';
    
    char *s=strtok(path,delim);
    while(s!=NULL){
       if(strcmp(s,"..")==0){
            //弹栈
          delete_catalog(list);
       }else if(strcmp(s,".")!=0){
            //压栈
          add_catalog(list,s);
       }
       s=strtok(NULL,delim);
    } 
    printf("已进入目录%s\n",dirName);
    return 0;
}

int pwd(Link_list_t *list,int user){
    //if(list==NULL || list->length==0){
    //    printf("%s\n",homepath);
    //    return 0;
    //}
    printf("当前目录为：");
    char buf[1024]="home/netdisk/C++66/";
    printf("%suser%d/",buf,user);
    
    printf_Linklist(list);    
    return 0;
}

int ls(char *file){
    if(file==NULL){
        printf("路径为NULL\n");
        return -1;
    }
    DIR *dirp=opendir(file);
    ERROR_CHECK(dirp,NULL,"打开文件失败");
    struct dirent *pdirent;
    printf("该目录下的内容为：\n");
    while((pdirent=readdir(dirp))!=NULL){
        printf("%s ",pdirent->d_name);
    }
    closedir(dirp);
    printf("\n");
    return 0;
}

int createDir(char *dir){
    if((access(dir,F_OK))==0){
        printf("该目录存在\n");
        return -1;
    }
    
    if((mkdir(dir,0755))==-1){
        printf("创建失败\n");
        return -2;
    }
    printf("创建目录%s成功\n",dir);
    return 0;
}

int deleteDir(char *dir){
    if((access(dir,F_OK))!=0){
       printf("该目录不存在\n");
       return -1;
    }
    int ret=rmdir(dir);
    if(ret==0){
        printf("删除目录%s成功\n",dir);
        return 0;
    }else{
        perror("删除失败\n");
        return -2;
    }
}


